#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import getopt

from config.default import *
from config.task_dic import get_task_dic

import logging
import logging.handlers

LOG_FILE = "./log/spider.log"


def init_log():
    logger = logging.getLogger()
    formatter = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    sh = logging.StreamHandler()  # 往屏幕上输出
    sh.setFormatter(formatter)  # 设置屏幕上显示的格式
    th = logging.handlers.TimedRotatingFileHandler(LOG_FILE, when='H', interval=1, backupCount=40)
    th.setFormatter(formatter)
    logger.addHandler(sh)
    logger.addHandler(th)
    logger.setLevel(logging.INFO)


def main():
    task_type = os.getenv('TASK_TYPE', '')
    if task_type == '':
        opts, args = getopt.getopt(sys.argv, "h", ["help"])
        if len(args) < 3:
            print('Usage: {} task_type action_type queue|except_queue|notify_queue')
            sys.exit(-1)
        task_type = args[1]
        action_type = args[2]
        queue_name = args[3] if len(args) >= 4 else task_type
    else:
        action_type = os.getenv('ACTION_TYPE', 'handler')
        queue_name = os.getenv('QUEUE', task_type)

    rds = get_rds()
    stat = get_stat(rds)
    # stat = None
    # 消息队列
    mq = get_mq(rds)
    # 代理
    # squid_proxy = get_squid_proxy()
    squid_proxy = None
    # 数据库连接
    mdb = get_mdb()

    config = {
        'name': task_type,
        'mq': mq,
        'queue_name': queue_name,
        'rds': rds,
        'stat': stat,
        'proxy': squid_proxy,
        'mdb': mdb
    }
    analyze_type = os.getenv('ANALYZE_TYPE')
    if analyze_type is not None:
        config['analyze_type'] = analyze_type

    handle_dic = get_task_dic()
    if task_type not in handle_dic or action_type not in handle_dic[task_type]:
        print('task_type {} no {} in task_dic'.format(task_type, action_type))
        sys.exit(-1)
    handle_class = handle_dic[task_type][action_type]
    handler = handle_class(config)
    handler.run()
    handler.close()


if __name__ == '__main__':
    init_log()
    main()
